package com.lqjava.flowable.serverapp.sys.config.api;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lqjava.flowable.beans.exceptions.ApiParamsException;
import com.lqjava.flowable.beans.exceptions.EnumException;
import com.lqjava.flowable.beans.exceptions.ServiceException;
import com.lqjava.flowable.beans.result.ResultBean;

import lombok.extern.slf4j.Slf4j;
/**
 * Api异常全局捕获器
 * 捕获全局异常 和自定义异常 并且统一格式返回
 * @author lq 2021年3月21日 19:15:22
 */
@Slf4j
@ControllerAdvice
public class ApiExceptionAdvice {

	/**
	 * 系统异常捕获
	 * 
	 * @param e
	 * @return
	 */
	@ResponseBody
	@ExceptionHandler(value = Exception.class)
	public ResultBean<String> errorHandler(Exception e,HttpServletResponse resp) {
		ResultBean<String> res = new ResultBean<>();
		res.initFalse(e.getMessage());
		resp.setStatus(500);
		e.printStackTrace();
		return res;
	}
	
	/**
	 * 系统异常捕获
	 * 
	 * @param e
	 * @return
	 */
	@ResponseBody
	@ExceptionHandler(value = ApiParamsException.class)
	public ResultBean<String> errorHandlerApiParamsException(ApiParamsException e,HttpServletResponse resp) {
		ResultBean<String> res = new ResultBean<>();
		res.initFalse(e.getMessage());
		res.setObj(e.getBody());
		resp.setStatus(200);
		return res;
	}
	
	/**
	 * 系统异常捕获
	 * 
	 * @param e
	 * @return
	 */
	@ResponseBody
	@ExceptionHandler(value = EnumException.class)
	public ResultBean<String> errorHandlerEnumException(EnumException e,HttpServletResponse resp) {
		ResultBean<String> res = new ResultBean<>();
		res.initFalse(e.getMessage());
		res.setObj(e.getBody());
		resp.setStatus(200);
		return res;
	}
	
	/**
	 * 系统异常捕获
	 * 
	 * @param e
	 * @return
	 */
	@ResponseBody
	@ExceptionHandler(value = ServiceException.class)
	public ResultBean<String> errorHandlerServiceException(ServiceException e,HttpServletResponse resp) {
		ResultBean<String> res = new ResultBean<>();
		res.initFalse(e.getMessage());
		res.setObj(e.getBody());
		resp.setStatus(200);
		return res;
	}
}
